//
//  BDAddAddressViewController.m
//  BadBoy
//
//  Created by wen on 2017/2/20.
//  Copyright © 2017年 niusaibing. All rights reserved.
//

#import "BDAddAddressViewController.h"
#import "BDAddAddressTableViewCell.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import "BDRuzhuCityChooseView.h"
#import "BDCityInfo.h"
#import "BDTextView.h"
#import "BDUserModel.h"

@interface BDAddAddressViewController ()<UITableViewDelegate,UITableViewDataSource,ABPeoplePickerNavigationControllerDelegate,UIGestureRecognizerDelegate>
@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) BDTextView *textView;
@property (nonatomic, strong) NSArray *datasource;

@end

@implementation BDAddAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    if (self.addressModel == nil) {
        self.title = ASLocalizedString(@"添加新地址");
    }else {
        self.title = ASLocalizedString(@"修改地址信息");
    }
    
    [self layoutSubviews];
    [self requestDatasource];
    
}

- (void)layoutSubviews{
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc]initWithTitle:ASLocalizedString(@"保存")style:UIBarButtonItemStyleDone target:self action:@selector(saveAddress)];
    self.navigationItem.rightBarButtonItem = rightButton;
    
}

//保存按钮
-(void)saveAddress{
    NSString *alert = nil;
    if (![self.addressModel.name isNotEmpty]) {
        alert = ASLocalizedString(@"请填写联系人姓名");
    }else if (![self.addressModel.mobile isNotEmpty]) {
        alert = ASLocalizedString(@"请填写联系人电话号码");
    }else if (self.addressModel.province_id == 0) {
        alert = ASLocalizedString(@"请选择所在地区");
    }else if (![self.textView.text isNotEmpty]) {
        alert = ASLocalizedString(@"请输入详细地址");
    }
    if (alert != nil) {
        [MBManager showCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]] title:alert clickHidden:NO clickBlock:nil];
        return;
    }
    NSDictionary *para = @{@"province_id":@(self.addressModel.province_id),
                           @"city_id":@(self.addressModel.city_id),
                           @"district_id":@(self.addressModel.district_id),
                           @"mobile":self.addressModel.mobile,
                           @"name":self.addressModel.name,
                           @"address":self.textView.text};
    
    NSString *url = nil;
    if (self.addressModel.address_id != 0) {
        url = [NSString stringWithFormat:@"%@user/address/%@", KBDBaseURL, @(self.addressModel.address_id)];
    }else{
        url = [NSString stringWithFormat:@"%@user/address", KBDBaseURL];
    }
    NSString *headValid = [BDUserModel getHeaderValidation];
    
    [MBManager showLoadingAlert:ASLocalizedString(@"请稍后")clickHidden:NO clickBlock:nil];
    
    RACSignal *signal = nil;
    NSString *signStr = @"";
    if (self.addressModel.address_id != 0) {
        signal = [[BDNetworkingServer yy_PUT:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
        signStr = ASLocalizedString(@"修改地址");
    }else{
        signal = [[BDNetworkingServer yy_POST:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
        signStr = ASLocalizedString(@"添加地址");
    }
    [signal subscribeNext:^(id  _Nullable x) {
//        [MBManager hideAlert];
        [MBManager showBriefAlert:[NSString stringWithFormat:ASLocalizedString(@"%@成功"), signStr] clickHidden:NO clickBlock:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshAddressList" object:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
//        [MBManager hideAlert];
        
        [MBManager showBriefAlert:[NSString stringWithFormat:ASLocalizedString(@"%@失败"), signStr] clickHidden:NO clickBlock:nil];
        
    }];
}

- (void)requestDatasource{
    if (self.addressModel == nil) {
        self.addressModel = [[BDUserAddressModel alloc] init];
    }
    self.datasource = @[@{@"title":ASLocalizedString(@"联系人    "), @"subTitle":[self.addressModel.name isNotEmpty] ? self.addressModel.name : @""},
                        @{@"title":ASLocalizedString(@"联系电话"), @"subTitle":[self.addressModel.mobile isNotEmpty] ? self.addressModel.mobile : @"", @"needAdd":@YES},
                        @{@"title":ASLocalizedString(@"所在地区"), @"subTitle":[self.addressModel.cityStr isNotEmpty] ? self.addressModel.cityStr : @"", @"notEdit":@YES},];
    self.textView.text = self.addressModel.address;
    [self.tableview reloadData];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BDAddAddressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"addAddressCell" forIndexPath:indexPath];
    [cell configeWithModel:self.datasource[indexPath.row] addButtonBlock:^{
        ABPeoplePickerNavigationController *peopleVC = [[ABPeoplePickerNavigationController alloc]init];
        peopleVC.peoplePickerDelegate = self;
        //设置状态栏为白色
        [self presentViewController:peopleVC animated:YES completion:nil];
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    } textfieldBlock:^(NSString *text) {
        if (indexPath.row == 0) {
            self.addressModel.name = text;
        }else if (indexPath.row == 1) {
            self.addressModel.mobile = text;
        }
    }];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 2) {
        [BDRuzhuCityChooseView showWithFinished:^(NSArray *array) {
            BDCityInfo *cityinfo1 = array.firstObject;
            self.addressModel.province_id = cityinfo1.infoID;
            BDCityInfo *cityinfo2 = array[1];
            self.addressModel.city_id = cityinfo2.infoID;
            BDCityInfo *cityinfo3 = array[2];
            self.addressModel.district_id = cityinfo3.infoID;
            
            [self requestDatasource];
        }];
    }
}

//进入通讯录获取手机号码
#pragma mark - ABPeoplePickerNavigationControllerDelegate

-(void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{
    ABMultiValueRef valueRef = ABRecordCopyValue(person, kABPersonPhoneProperty);
    CFIndex index = ABMultiValueGetIndexForIdentifier(valueRef, identifier);
    //电话号码
    CFStringRef telvalue = ABMultiValueCopyValueAtIndex(valueRef, index);
    
    [self dismissViewControllerAnimated:YES completion:^{
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
        self.addressModel.mobile = (__bridge NSString *)telvalue;
        [self requestDatasource];
    }];
}
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker{
    // 更改状态栏的颜色为白色
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}

- (UITableView *)tableview{
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight) style:UITableViewStylePlain];
        _tableview.dataSource = self;
        _tableview.delegate = self;
        _tableview.backgroundColor = [UIColor clearColor];
        _tableview.tableFooterView = self.textView;
        _tableview.separatorInset = UIEdgeInsetsZero;
        [_tableview registerClass:[BDAddAddressTableViewCell class] forCellReuseIdentifier:@"addAddressCell"];
        [self.view addSubview:_tableview];
    }
    return _tableview;
}

- (UIView *)customTableViewFooterView{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 100)];
    view.backgroundColor = self.textView.backgroundColor;
    view.layer.borderColor = kBDColorGray.CGColor;
    view.layer.borderWidth = 1;
    [view addSubview:self.textView];
    return view;
}

- (BDTextView *)textView{
    if (!_textView) {
        self.textView = [[BDTextView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 100)];
        _textView.placeholder = ASLocalizedString(@"请填写详细地址");
        _textView.textColor = KBDNameColor;
        _textView.font = [UIFont systemFontOfSize:14];
//        [_textView.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
//            self.addressModel.address = _textView.text;
//        }];
        _textView.layer.borderColor = kBDColorGray.CGColor;
        _textView.layer.borderWidth = 1;
    }
    return _textView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
